<template>
  <div class="workflow-definition-page">
    <!-- 查询表单 -->
    <DefinitionSearchForm
      :loading="loading"
      @search="handleSearch"
      @reset="handleReset"
      @update:search-params="handleSearchParamsChange"
    />
    
    <!-- 流程定义列表 -->
    <DefinitionList
      :table-data="tableData"
      :pagination="pagination"
      :loading="loading"
      :selection="selection"
      @update:selection="handleSelectionChange"
      @page-change="handlePageChange"
      @sort="handleSort"
      @refresh="handleRefresh"
      @export="handleExport"
      @add="handleAdd"
      @action="handleAction"
    />
    
    <!-- 新增流程定义弹窗 -->
    <DefinitionAddDialog
      v-model:visible="addDialogVisible"
      :loading="dialogLoading"
      :category-options="categoryOptions"
      @submit="handleAddSubmit"
      @close="handleAddClose"
    />
    
    <!-- 编辑流程定义弹窗 -->
    <DefinitionEditDialog
      v-model:visible="editDialogVisible"
      :definition-data="editingDefinition"
      :category-options="categoryOptions"
      :loading="dialogLoading"
      @submit="handleEditSubmit"
      @close="handleEditClose"
    />
    
    <!-- BPMN流程设计器弹窗 -->
    <BpmnDesigner
      v-model:visible="designerVisible"
      :initial-xml="currentDefinitionXml"
      @save="handleDesignerSave"
      @close="handleDesignerClose"
    />
    
    <!-- 删除确认弹窗 -->
    <ConfirmDialog
      v-model:visible="deleteConfirmVisible"
      type="danger"
      title="删除确认"
      :message="deleteConfirmMessage"
      confirm-text="删除"
      cancel-text="取消"
      @confirm="handleDeleteConfirm"
      @cancel="handleDeleteCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import DefinitionSearchForm from './modules/DefinitionSearchForm.vue'
import DefinitionList from './modules/DefinitionList.vue'
import DefinitionAddDialog from './modules/DefinitionAddDialog.vue'
import DefinitionEditDialog from './modules/DefinitionEditDialog.vue'
import BpmnDesigner from '../../../components/BpmnDesigner/EnhancedBpmnDesigner.vue'
import ConfirmDialog from '@/components/ConfirmDialog/index.vue'
import type { Pagination, TableAction } from '@/types'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const dialogLoading = ref(false)
const selection = ref<any[]>([])
const searchParams = ref({})

// 弹窗状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const editingDefinition = ref<any>(null)

// BPMN设计器状态
const designerVisible = ref(false)
const currentDefinitionXml = ref('')
const currentDefinitionId = ref<number | null>(null)

// 删除确认状态
const deleteConfirmVisible = ref(false)
const deleteConfirmMessage = ref('')
const deletingDefinitionId = ref('')

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 分类选项
const categoryOptions = [
  { label: '请假流程', value: 1 },
  { label: '报销流程', value: 2 },
  { label: '审批流程', value: 3 },
  { label: '采购流程', value: 4 }
]

const tableData = ref([
  {
    id: 1,
    name: '员工请假申请流程',
    modelKey: 'leave_process',
    categoryId: 1,
    modelXml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn">
  <bpmn:process id="Process_1" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" />
    <bpmn:userTask id="UserTask_1" name="填写请假申请" />
    <bpmn:userTask id="UserTask_2" name="部门经理审批" />
    <bpmn:endEvent id="EndEvent_1" />
    <bpmn:sequenceFlow id="Flow_1" sourceRef="StartEvent_1" targetRef="UserTask_1" />
    <bpmn:sequenceFlow id="Flow_2" sourceRef="UserTask_1" targetRef="UserTask_2" />
    <bpmn:sequenceFlow id="Flow_3" sourceRef="UserTask_2" targetRef="EndEvent_1" />
  </bpmn:process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_1">
    <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
      <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1">
        <dc:Bounds x="179" y="159" width="36" height="36" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_UserTask_1" bpmnElement="UserTask_1">
        <dc:Bounds x="270" y="137" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_UserTask_2" bpmnElement="UserTask_2">
        <dc:Bounds x="450" y="137" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_EndEvent_2" bpmnElement="EndEvent_1">
        <dc:Bounds x="632" y="161" width="36" height="36" />
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</bpmn:definitions>`,
    version: 1,
    createTime: '2024-01-01 10:00:00',
    delFlag: 0
  },
  {
    id: 2,
    name: '差旅报销流程',
    modelKey: 'travel_expense',
    categoryId: 2,
    modelXml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_2" targetNamespace="http://bpmn.io/schema/bpmn">
  <bpmn:process id="Process_2" isExecutable="true">
    <bpmn:startEvent id="StartEvent_2" />
    <bpmn:userTask id="UserTask_3" name="填写报销单" />
    <bpmn:exclusiveGateway id="Gateway_1" />
    <bpmn:userTask id="UserTask_4" name="财务审批" />
    <bpmn:endEvent id="EndEvent_2" />
    <bpmn:sequenceFlow id="Flow_4" sourceRef="StartEvent_2" targetRef="UserTask_3" />
    <bpmn:sequenceFlow id="Flow_5" sourceRef="UserTask_3" targetRef="Gateway_1" />
    <bpmn:sequenceFlow id="Flow_6" sourceRef="Gateway_1" targetRef="UserTask_4" />
    <bpmn:sequenceFlow id="Flow_7" sourceRef="UserTask_4" targetRef="EndEvent_2" />
  </bpmn:process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_2">
    <bpmndi:BPMNPlane id="BPMNPlane_2" bpmnElement="Process_2">
      <bpmndi:BPMNShape id="_BPMNShape_StartEvent_3" bpmnElement="StartEvent_2">
        <dc:Bounds x="179" y="159" width="36" height="36" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_UserTask_3" bpmnElement="UserTask_3">
        <dc:Bounds x="270" y="137" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_Gateway_1" bpmnElement="Gateway_1">
        <dc:Bounds x="415" y="152" width="50" height="50" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_UserTask_4" bpmnElement="UserTask_4">
        <dc:Bounds x="520" y="137" width="100" height="80" />
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape id="_BPMNShape_EndEvent_3" bpmnElement="EndEvent_2">
        <dc:Bounds x="702" y="161" width="36" height="36" />
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</bpmn:definitions>`,
    version: 2,
    createTime: '2024-01-02 09:15:00',
    delFlag: 0
  },
  {
    id: 3,
    name: '采购申请流程',
    modelKey: 'purchase_request',
    categoryId: 4,
    modelXml: '',
    version: 1,
    createTime: '2024-01-03 11:30:00',
    delFlag: 0
  },
  {
    id: 4,
    name: '合同审批流程',
    modelKey: 'contract_approval',
    categoryId: 3,
    modelXml: '',
    version: 3,
    createTime: '2024-01-04 14:45:00',
    delFlag: 0
  },
  {
    id: 5,
    name: '加班申请流程',
    modelKey: 'overtime_request',
    categoryId: 1,
    modelXml: '',
    version: 1,
    createTime: '2024-01-05 16:20:00',
    delFlag: 0
  }
])

// 初始化数据
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新分页信息
    pagination.total = 20 // 模拟总数
    
    console.log('加载流程定义数据:', {
      searchParams: searchParams.value,
      pagination: pagination
    })
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索参数变化
const handleSearchParamsChange = (params: Record<string, any>) => {
  searchParams.value = params
}

// 处理搜索
const handleSearch = (params: Record<string, any>) => {
  console.log('搜索参数:', params)
  searchParams.value = params
  pagination.currentPage = 1
  loadData()
}

// 处理重置
const handleReset = () => {
  console.log('重置搜索')
  searchParams.value = {}
  pagination.currentPage = 1
  loadData()
}

// 处理选择变化
const handleSelectionChange = (newSelection: any[]) => {
  console.log('选择变化:', newSelection)
  selection.value = newSelection
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  console.log('分页变化:', page, pageSize)
  pagination.currentPage = page
  pagination.pageSize = pageSize
  loadData()
}

// 处理排序
const handleSort = (sortField: string, sortOrder: number) => {
  console.log('排序变化:', sortField, sortOrder)
  loadData()
}

// 处理刷新
const handleRefresh = () => {
  console.log('刷新数据')
  loadData()
}

// 处理导出
const handleExport = () => {
  console.log('导出数据')
  // 实现导出逻辑
}

// 处理新增
const handleAdd = () => {
  console.log('新增流程定义')
  addDialogVisible.value = true
}

// 处理操作
const handleAction = async (action: TableAction, row: any, index: number) => {
  console.log('执行操作:', action.key, row, index)
  
  switch (action.key) {
    case 'edit':
      editingDefinition.value = row
      editDialogVisible.value = true
      break
    case 'view':
      router.push(`/workflow/definition/detail/${row.id}`)
      break
    case 'design':
      openBpmnDesigner(row)
      break
    case 'delete':
      deleteConfirmMessage.value = `您确定要删除流程定义 "${row.name}" 吗？删除后将无法恢复。`
      deletingDefinitionId.value = row.id
      deleteConfirmVisible.value = true
      break
  }
}

// 处理新增提交
const handleAddSubmit = async (data: any) => {
  dialogLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 添加到表格数据
    const newDefinition = {
      id: Date.now(),
      ...data,
      version: 1,
      createTime: new Date().toLocaleString('zh-CN'),
      delFlag: 0
    }
    
    tableData.value.unshift(newDefinition)
    pagination.total++
    
    addDialogVisible.value = false
    console.log('新增流程定义成功:', newDefinition)
  } catch (error) {
    console.error('新增流程定义失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 处理新增关闭
const handleAddClose = () => {
  addDialogVisible.value = false
}

// 处理编辑提交
const handleEditSubmit = async (data: any) => {
  dialogLoading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新表格数据
    const index = tableData.value.findIndex(item => item.id === data.id)
    if (index > -1) {
      tableData.value[index] = {
        ...tableData.value[index],
        ...data,
        version: tableData.value[index].version + 1
      }
    }
    
    editDialogVisible.value = false
    editingDefinition.value = null
    console.log('编辑流程定义成功:', data)
  } catch (error) {
    console.error('编辑流程定义失败:', error)
  } finally {
    dialogLoading.value = false
  }
}

// 处理编辑关闭
const handleEditClose = () => {
  editDialogVisible.value = false
  editingDefinition.value = null
}

// 打开BPMN设计器
const openBpmnDesigner = (definition: any) => {
  console.log('打开BPMN设计器:', definition)
  currentDefinitionId.value = definition.id
  currentDefinitionXml.value = definition.modelXml || ''
  designerVisible.value = true
}

// 处理BPMN设计器保存
const handleDesignerSave = async (xml: string) => {
  console.log('保存BPMN设计:', xml)
  
  if (!currentDefinitionId.value) {
    console.error('没有找到当前流程定义ID')
    return
  }
  
  try {
    // 模拟API调用保存XML
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新表格数据中的modelXml
    const index = tableData.value.findIndex(item => item.id === currentDefinitionId.value)
    if (index > -1) {
      tableData.value[index].modelXml = xml
      tableData.value[index].version = (tableData.value[index].version || 1) + 1
    }
    
    designerVisible.value = false
    currentDefinitionId.value = null
    currentDefinitionXml.value = ''
    
    console.log('BPMN设计保存成功')
  } catch (error) {
    console.error('BPMN设计保存失败:', error)
  }
}

// 处理BPMN设计器关闭
const handleDesignerClose = () => {
  designerVisible.value = false
  currentDefinitionId.value = null
  currentDefinitionXml.value = ''
}

// 处理删除确认
const handleDeleteConfirm = () => {
  if (deletingDefinitionId.value) {
    deleteDefinition(deletingDefinitionId.value)
  }
  deleteConfirmVisible.value = false
  deletingDefinitionId.value = ''
  deleteConfirmMessage.value = ''
}

// 处理删除取消
const handleDeleteCancel = () => {
  deleteConfirmVisible.value = false
  deletingDefinitionId.value = ''
  deleteConfirmMessage.value = ''
}

// 删除流程定义
const deleteDefinition = async (id: number) => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 从表格数据中移除
    const index = tableData.value.findIndex(item => item.id === id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.total--
    }
    
    console.log('删除流程定义成功:', id)
  } catch (error) {
    console.error('删除流程定义失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.workflow-definition-page {
  padding: 0;
}
</style>